<template>
  <el-card class="department">
    <template #header>
      <div class="card-header">
        <span
          >部门管理
          <el-button-group style="margin-left: 20px">
            <el-button plain type="primary" @click="System.departmentsDelete()"
              ><span>批量删除</span></el-button
            >
            <el-button plain type="primary" @click="System.departmentAdd()"
              ><span>新建部门</span></el-button
            >
          </el-button-group>
        </span>
        <span>
          <el-input v-model="search" placeholder="查找">
            <template #suffix>
              <el-icon><IEpSearch></IEpSearch></el-icon>
            </template> </el-input
        ></span>
        <span class="fileOperation">
          <el-upload
            ref="departmentFiles"
            v-model:file-list="System.department.departmentFile"
            :show-file-list="false"
            :limit="1"
            :on-exceed="departmentUploadExceed"
            :auto-upload="false"
            :on-change="departmentUploadChange"
          >
            <el-tooltip
              effect="dark"
              content="请上传前确保格式相同，系统不做格式验证"
              placement="left"
            >
              <el-button plain type="primary">
                导入
                <el-icon :size="20"
                  ><IAntDesignCloudUploadOutlined></IAntDesignCloudUploadOutlined
                ></el-icon>
              </el-button>
            </el-tooltip>
            <template #tip>
              <div class="el-upload__tip">文件最大限制1024KB</div>
            </template>
          </el-upload>

          <el-dropdown>
            <el-button plain type="primary">
              导出<el-icon :size="20"
                ><IAntDesignCloudDownloadOutlined></IAntDesignCloudDownloadOutlined
              ></el-icon>
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item @click="System.exportJson(2)"
                  >导出json</el-dropdown-item
                >
                <el-dropdown-item divided>导出其他格式</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </span>
      </div>
    </template>
    <el-table
      ref="departmentTableSelect"
      :data="
        getData.slice(
          System.department.pageSize * (System.department.currentPage - 1),
          System.department.pageSize * System.department.currentPage
        )
      "
      row-key="id"
      :indent="10"
      border
      @selection-change="System.selectionChange"
      @select-all="selectAll"
      @select="selectRow"
    >
      <template #empty>
        {{ $t("default.noData") }}
      </template>

      <el-table-column align="center" type="selection" width="80" />
      <el-table-column
        header-align="center"
        prop="id"
        label="用户编号"
        width="150"
        fixed
      />
      <el-table-column
        align="center"
        prop="name"
        label="公司名称"
        width="250"
      />
      <el-table-column
        align="center"
        prop="legalRepresentative"
        label="公司法人"
      />
      <el-table-column
        align="center"
        prop="phone"
        label="联系电话"
        width="150"
      />
      <el-table-column
        align="center"
        prop="email"
        label="联系邮箱"
        width="200"
      />
      <el-table-column
        align="center"
        prop="date"
        label="创建时间"
        width="150"
      />
      <el-table-column align="center" fixed="right" label="操作" width="180">
        <template #default="scope">
          <el-button-group>
            <el-button
              type="primary"
              text
              @click="System.departmentEditOrDelete(1, scope.row)"
              :disabled="scope.row.parent == 0"
              >修改<el-icon><IEpEdit></IEpEdit></el-icon
            ></el-button>
            <el-button
              type="primary"
              text
              @click="System.departmentEditOrDelete(0, scope.row)"
              :disabled="scope.row.parent == 0"
              >删除<el-icon><IEpDelete></IEpDelete></el-icon
            ></el-button>
          </el-button-group>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination">
      <el-pagination
        v-model:currentPage="System.department.currentPage"
        v-model:page-size="System.department.pageSize"
        :disabled="false"
        :background="false"
        layout="total,sizes,prev, pager, next, jumper"
        :total="getData.length"
        :page-sizes="[10, 20, 30, 40, 50]"
      />
    </div>
    <el-dialog
      v-model="System.department.isDialogDisplay"
      title="用户信息"
      @open="openForm()"
    >
      <el-form :model="System.department.departmentForm">
        <el-form-item label="公司名称" label-width="140px" required>
          <el-input v-model="System.department.departmentForm.name" />
        </el-form-item>
        <el-form-item label="公司法人" label-width="140px" required>
          <el-input
            v-model="System.department.departmentForm.legalRepresentative"
          />
        </el-form-item>
        <el-form-item label="联系电话" label-width="140px" required>
          <el-input v-model="System.department.departmentForm.phone" />
        </el-form-item>
        <el-form-item label="联系邮箱" label-width="140px">
          <el-input v-model="System.department.departmentForm.email" />
        </el-form-item>
        <el-form-item label="父节点" label-width="140px" required>
          <el-scrollbar max-height="150px">
            <el-tree
              ref="departmentTree"
              :data="getDepartmentTreeData()"
              :props="System.department.props"
              node-key="id"
              :check-strictly="true"
              show-checkbox
              empty-text="根节点无法更换"
              @check="selectTree"
            >
              <template #default="{ data: { name } }">
                <span> {{ name }}</span>
              </template>
            </el-tree>
          </el-scrollbar>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="System.departmentSaveOrCancel(0)">取消</el-button>
          <el-button type="primary" @click="System.departmentSaveOrCancel(1)"
            >保存</el-button
          >
        </span>
      </template>
    </el-dialog>
  </el-card>
</template>
<script lang="ts">
export default {
  // name: "department",
};
</script>
<script setup lang="ts">
import {
  ElMessageBox,
  ElTable,
  ElTree,
  genFileId,
  UploadFile,
  UploadFiles,
} from "element-plus";
import Node from "element-plus/es/components/tree/src/model/node";
import { useSystem } from "../../../store/system";
import type { UploadInstance, UploadProps, UploadRawFile } from "element-plus";
const System = useSystem();

const all = (data: any, type: number) => {
  if (data.length != 0) {
    type == 1
      ? (() => {
          for (let i in data) {
            departmentTableSelect.value!.toggleRowSelection(data[i], true);
            all(data[i].children, type);
          }
        })()
      : (() => {
          for (let i in data) {
            departmentTableSelect.value!.toggleRowSelection(data[i], false);
            all(data[i].children, type);
          }
        })();
  }
  return;
};
const departmentTableSelect = ref<InstanceType<typeof ElTable>>();
const selectAll = () => {
  departmentTableSelect.value!.getSelectionRows().length !=
  System.department.length - System.department.departments.length
    ? all(
        getData.value.slice(
          System.department.pageSize * (System.department.currentPage - 1),
          System.department.pageSize * System.department.currentPage
        ),
        1
      )
    : departmentTableSelect.value!.clearSelection();
};

const selectRow = (selection: any, row: any) => {
  //为空时修改全选框状态
  if (selection.length == 0) departmentTableSelect.value!.clearSelection();

  if (selection.findIndex((v: any) => v.id == row.id) > -1)
    all(row.children, 1);
  else all(row.children, 0);
};

//文件上传
const departmentFiles = ref<UploadInstance>();

const departmentUploadExceed: UploadProps["onExceed"] = (files) => {
  departmentFiles.value!.clearFiles();
  const file = files[0] as UploadRawFile;
  file.uid = genFileId();
  departmentFiles.value!.handleStart(file);
};

const departmentUploadChange: UploadProps["onChange"] = (
  uploadFile: UploadFile,
  uploadFiles: UploadFiles
) => {
  ElMessageBox.confirm(
    `是否导入<strong><i>${uploadFile.name}</i></strong>文件内容`,
    "注意：导入前请保存原有内容，内容丢失后果由个人承担！",
    {
      confirmButtonText: "确认",
      cancelButtonText: "取消",
      showClose: false,
      type: "error",
      dangerouslyUseHTMLString: true,
    }
  )
    .then(() => {
      const reader = new FileReader();
      reader.readAsText(uploadFile.raw as Blob, "UTF-8");
      reader.onload = (e) => {
        const dataJson = JSON.parse(e.target?.result as string);
        System.department.departments = dataJson;
      };
      ElMessage({
        type: "success",
        message: "成功导入！",
        duration: 500,
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消导入！",
        duration: 500,
      });
    });
};
// const beforeUpload: UploadProps["beforeUpload"] = (
//   rawFile: UploadRawFile
// ): Awaitable<void | undefined | null | boolean | File | Blob> => {
//   const reader = new FileReader();
//   reader.readAsText(rawFile, "UTF-8");
//   reader.onload = (e) => {
//     const dataJson = JSON.parse(e.target?.result as string);
//     System.department.departments = dataJson;
//   };
// };
// const uploadSuccess: UploadProps["onSuccess"] = (
//   response: any,
//   uploadFile: UploadFile,
//   uploadFiles: UploadFiles
// ) => {
// };
// const uploadError: UploadProps["onError"] = (
//   error: Error,
//   uploadFile: UploadFile,
//   uploadFiles: UploadFiles
// ) => {
// };

//搜索功能
const search = ref("");
const getData = computed(() =>
  System.department.departments.filter(
    (data: { name: string }) =>
      !search.value ||
      data.name.toLowerCase().includes(search.value.toLowerCase())
  )
);

//树形选择数据不能选取自身和子孙节点
const recursive = (id: number, arr: any[]): any[] => {
  if (arr.length != 0) {
    let index = arr.findIndex((v: any) => v.id == id);
    if (index > -1) {
      arr.splice(index, 1);
      return arr;
    }
    for (let i in arr) {
      recursive(id, arr[i].children);
    }
  }
  return arr;
};
const getDepartmentTreeData = (): any[] => {
  return System.department.departmentForm.id == 0
    ? JSON.parse(JSON.stringify(System.department.departments))
    : recursive(
        System.department.departmentForm.id,
        JSON.parse(JSON.stringify(System.department.departments))
      );
};

//父节点选中
const departmentTree = ref<InstanceType<typeof ElTree>>();

const selectTree = (x: Node) => {
  departmentTree.value!.setCheckedKeys([x.id], false);
  System.department.departmentForm.parent = x.id;
};

const openForm = () => {
  //显示保存的选择状态
  departmentTree.value!.setCheckedKeys(
    [System.department.departmentForm.parent],
    false
  );
};
</script>
<style scoped lang="scss">
.department {
  position: relative;
  left: -20px;
  top: -20px;
  width: calc(100% + 40px);
  height: calc(100% + 20px);
  border: 0px;

  display: flex;
  flex-direction: column;
  .card-header {
    display: flex;
    justify-content: space-between;
    .fileOperation {
      display: flex;
    }
  }
  > :deep(.el-card__body) {
    flex-grow: 1;
    flex-basis: 0;
    padding: 0px;

    display: flex;
    flex-direction: column;

    .el-table {
      flex-grow: 1;
      flex-basis: 0;
    }
    .pagination {
      height: 50px;
      display: flex;
      justify-content: center;
      margin-top: 5px;
    }
  }
}

.el-scrollbar {
  border-radius: 5px;
  border: 2px solid rgb(231, 231, 231);
  width: 100%;
  .el-tree {
    min-height: 150px;
  }
}
</style>
